package fr.unice.polytech.plim.podometre;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;




public class ServiceBDD extends Service {
	
	private LocationManager locationManager;
	public SQLiteDatabase bdd ;
	public Bdd mabase = new Bdd(this, Bdd.DATABASE_NAME, null, Bdd.DATABASE_VERSION);
	ContentValues nouvelleValeurs = new ContentValues();
	
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(context);
		setBdd(mabase.getWritableDatabase());
		bdd.delete(Bdd.DATABASE_TABLE,"1",null);
		
		Criteria criteria = new Criteria();
	    criteria.setAccuracy(Criteria.ACCURACY_FINE);
	    criteria.setAltitudeRequired(false);
	    criteria.setBearingRequired(false);
	    criteria.setCostAllowed(true);
	    criteria.setPowerRequirement(Criteria.POWER_LOW);
	    String provider = locationManager.getBestProvider(criteria, true);
		Location location = locationManager.getLastKnownLocation(provider);
		updateWithNewLocation(location);
		locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
		bdd.close();
	}
	private final LocationListener locationListener = new LocationListener() {
		
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
			
		}
		
		@Override
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
			
		}
	};
	
	private void updateWithNewLocation(Location location) {
		if (location != null){
			double lat = location.getLatitude();
			double llg = location.getLongitude();
			double alt = location.getAltitude();
			double speed = location.getSpeed();
			long time = location.getTime();
			
			nouvelleValeurs.put(Bdd.KEY_DATE, time);
			nouvelleValeurs.put(Bdd.KEY_POSITION_ALT,alt );
			nouvelleValeurs.put(Bdd.KEY_POSITION_LAT, lat);
			nouvelleValeurs.put(Bdd.KEY_POSITION_LONG, llg);
			nouvelleValeurs.put(Bdd.KEY_VITESSE, speed);
			bdd.insert(Bdd.DATABASE_TABLE, null, nouvelleValeurs);
			
		}	
	}
	
	public SQLiteDatabase getBdd() {
		return bdd;
	}


	public void setBdd(SQLiteDatabase bdd) {
		this.bdd = bdd;
	}
	
}